/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { useEffect, useState } from 'react';
import { BreakpointManager } from './BreakpointManager';
import { heightBreakpointMap, HeightBreakpoint } from '../config/breakpoints/types';
import { heightBreakpoints, heightBreakpointsMap } from "../config/breakpoints/breakpoints";

export function useHeightBreakpointValue<T>(values: heightBreakpointMap<T>, referenceHeight?: number): T | undefined {
    const breakpointManager = BreakpointManager.getInstance();
    const [currentHeightBreakpoint, setCurrentHeightBreakpoint] = useState<HeightBreakpoint>(breakpointManager.getCurrentHeightBreakpoint() as HeightBreakpoint);

    useEffect(() => {
        // 如果传入 referenceHeight，直接计算断点并返回
        if (referenceHeight !== undefined) {
            const calculatedBreakpoint = breakpointManager.calculateBreakpoint(referenceHeight, heightBreakpointsMap) as HeightBreakpoint;
            setCurrentHeightBreakpoint(calculatedBreakpoint);
            return; // 直接返回，不需要订阅
        }
        // 订阅断点变化
        const unsubscribe = breakpointManager.subscribeToBreakpoint(
            (_, newHeightBreakpoint) => {
                setCurrentHeightBreakpoint(newHeightBreakpoint as HeightBreakpoint);
            }
        );

        // 清理订阅
        return () => {
            unsubscribe();
        };
    }, [referenceHeight]);

    // 根据当前纵向断点选择值
    let result = values[currentHeightBreakpoint];

    // 如果当前断点值为 null 或 undefined，遍历返回上一级断点的值，直到匹配为止
    if (result === null || result === undefined) {
        heightBreakpoints.forEach((breakpoint, index) => {
            if (breakpoint === currentHeightBreakpoint) {
                // 从当前断点开始向上查找
                for (let i = index - 1; i >= 0; i--) {
                    const previousBreakpoint = heightBreakpoints[i];
                    const preValue = values[previousBreakpoint];
                    if (preValue !== null && preValue !== undefined) {
                        result = preValue;
                        break;
                    }
                }
            }
        })
    }

    return result ?? values.base; // 如果没有匹配到任何值，返回 base 值
}
